package com.sam.springboot.algorithm;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @classname: RoundRobin
 * @description: 普通轮询算法
 * 按顺序依次循环分配
 * @Author: sam
 * @date: 2022/5/21 10:21
 */
@Slf4j
public class RoundRobinV1 {

    private static Integer index = 0;
    private static List<String> nodes = new ArrayList<>();
    // 准备模拟数据
    static {
        nodes.add("192.168.0.1");
        nodes.add("192.168.0.2");
        nodes.add("192.168.0.3");
        System.out.println("普通轮询算法的所有节点："+nodes);//打印所有节点
    }

    // 关键代码
    public String selectNode(){
        String ip = null;
        synchronized (index){
            // 下标复位
            if(index>=nodes.size()) index = 0;
            ip = nodes.get(index);
            index++;
        }
        return ip;
    }

    // 并发测试：两个线程循环获取节点
    public static void main(String[] args) {
        new Thread(() -> {
            RoundRobinV1 roundRobin1 = new RoundRobinV1();
            for (int i=1;i<=10;i++){
                String serverIp = roundRobin1.selectNode();
                System.out.println(Thread.currentThread().getName()+"==第"+i+"次获取节点："+serverIp);
            }
        }).start();

        /*new Thread(() -> {
            RoundRobinV1 roundRobin1 = new RoundRobinV1();
            for (int i=1;i<=5;i++){
                String serverIp = roundRobin1.selectNode();
                System.out.println(Thread.currentThread().getName()+"==第"+i+"次获取节点："+serverIp);
            }
        }).start();*/


        RoundRobinV1 roundRobin2 = new RoundRobinV1();
        for (int i=1;i<=10;i++){
            String serverIp = roundRobin2.selectNode();
            System.out.println(Thread.currentThread().getName()+"==第"+i+"次获取节点："+serverIp);
        }
    }
}
